package com.example.jwtauthdemo.service.impl;



import com.example.jwtauthdemo.dao.Student;
import com.example.jwtauthdemo.vo.StudentApplicationVO;
import com.example.jwtauthdemo.mapper.StudentManageMapper;
import com.example.jwtauthdemo.service.StudentManageService;
import com.example.jwtauthdemo.util.ResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.jwtauthdemo.exception.ServiceException;


import java.util.List;

@Service
@RequiredArgsConstructor
public class StudentManageServiceImpl implements StudentManageService {
    private static final Logger log = LoggerFactory.getLogger(StudentManageServiceImpl.class);
    @Autowired
    private StudentManageMapper studentManageMapper;

    @Override
    public List<Student> selectStudentInfo(String classCode, String teacherId) {

        return studentManageMapper.selectStudentInfo(classCode, teacherId);

    }

    @Override
    public int removeStudent(Integer classCode, Integer studentId, Integer teacherId) {
        try {
            log.info("教师{}移除学生{}从班级{}", teacherId, studentId, classCode);
            int result = studentManageMapper.removeStudent(classCode, studentId, teacherId);
            
            // 将学生在user表的class_id设为null
            if (result > 0) {
                log.info("开始将学生{}的班级ID设为null", studentId);
                updateUserClassId(studentId, null);
            }
            
            return result;
        } catch (Exception e) {
            log.error("移除学生失败: classCode={}, studentId={}, teacherId={}, 错误信息={}", 
                      classCode, studentId, teacherId, e.getMessage());
            log.error("移除学生异常堆栈", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "移除学生失败: " + e.getMessage());
        }
    }
    @Override
    public int agreeStudent(Integer classCode, Integer studentId, Integer teacherId) {
        try {
            // 学生角色为0
            Integer role = 0;
            log.info("教师{}同意学生{}加入班级{}", teacherId, studentId, classCode);
            int result = studentManageMapper.agreeStudent(classCode, studentId, role);
            
            // 更新用户的班级ID
            if (result > 0) {
                log.info("开始更新学生{}的班级ID为{}", studentId, classCode);
                updateUserClassId(studentId, classCode);
            }

            System.out.println("已同意学生加入班级");
            return result;
        } catch (Exception e) {
            log.error("同意学生加入班级失败: classCode={}, studentId={}, teacherId={}, 错误信息={}", 
                      classCode, studentId, teacherId, e.getMessage());
            log.error("同意学生加入班级异常堆栈", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "同意学生加入班级失败: " + e.getMessage());
        }
    }
    @Override
    public List<StudentApplicationVO> getPendingStudentApplications(Integer teacherId) {
        try {
            log.info("查询教师{}所教班级的待同意学生申请并关联用户信息", teacherId);
            return studentManageMapper.selectPendingStudentApplications(teacherId);
        } catch (Exception e) {
            log.error("查询待同意学生申请失败: teacherId={}, 错误信息={}", teacherId, e.getMessage());
            log.error("查询待同意学生申请异常堆栈", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "查询待同意学生申请失败: " + e.getMessage());
        }
    }
    @Override
    public int updateStudentApplicationStatus(Integer userId, Integer status) {
        try {
            // 验证status参数的有效值（1表示同意，2表示拒绝）
            if (status != 1 && status != 2) {
                log.error("更新学生申请状态失败: 无效的状态值={}", status);
                throw new ServiceException(ResultCode.BAD_REQUEST, "无效的状态值，只能是1（同意）或2（拒绝）");
            }
            
            log.info("更新学生{}的申请状态为{}", userId, status == 1 ? "同意" : "拒绝");
            int result = studentManageMapper.updateStudentApplicationStatus(userId, status);
            
            if (result == 0) {
                log.warn("未找到用户{}的申请记录", userId);
                throw new ServiceException(ResultCode.NOT_FOUND, "未找到该用户的申请记录");
            }
            
            return result;
        } catch (ServiceException e) {
            // 直接抛出已经格式化的ServiceException
            throw e;
        } catch (Exception e) {
            log.error("更新学生申请状态失败: userId={}, status={}, 错误信息={}", userId, status, e.getMessage());
            log.error("更新学生申请状态异常堆栈", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "更新学生申请状态失败: " + e.getMessage());
        }
    }
    @Override
    public int teacherApplyForClass(Integer teacherId, Integer classCode, Integer status) {
        try {
            // 验证status参数的有效值（0表示待同意状态）
            if (status != 0) {
                log.error("教师申请加入班级失败: 无效的状态值={}", status);
                throw new ServiceException(ResultCode.BAD_REQUEST, "无效的状态值，教师申请只能是0（待同意）");
            }
            
            log.info("教师{}申请加入班级{}", teacherId, classCode);
            int result = studentManageMapper.teacherApplyForClass(teacherId, classCode, status);
            
            return result;
        } catch (ServiceException e) {
            // 直接抛出已经格式化的ServiceException
            throw e;
        } catch (Exception e) {
            log.error("教师申请加入班级失败: teacherId={}, classCode={}, 错误信息={}", teacherId, classCode, e.getMessage());
            log.error("教师申请加入班级异常堆栈", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "教师申请加入班级失败: " + e.getMessage());
        }
    }
    
    @Override
    public int updateUserClassId(Integer userId, Integer classCode) {
        try {
            log.info("更新用户{}的班级ID为{}", userId, classCode);
            return studentManageMapper.updateUserClassId(userId, classCode);
        } catch (Exception e) {
            log.error("更新用户班级ID失败: userId={}, classCode={}, 错误信息={}", userId, classCode, e.getMessage());
            log.error("更新用户班级ID异常堆栈", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "更新用户班级ID失败: " + e.getMessage());
        }
    }

    @Override
    public List<StudentApplicationVO> getApprovedApplications(Integer teacherId) {
        try {
            log.info("查询教师{}所教班级的已同意或拒绝学生申请并关联用户信息", teacherId);
            return studentManageMapper.selectApprovedApplications(teacherId);
        } catch (Exception e) {
            log.error("查询已同意或拒绝学生申请失败: teacherId={}, 错误信息={}", teacherId, e.getMessage());
            log.error("查询已同意或拒绝学生申请异常堆栈", e);
            throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR, "查询已同意或拒绝学生申请失败: " + e.getMessage());
        }
    }
}
